﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenPhotoAlbum.DbAccess;
using OpenPhotoAlbum.BusinessLogics.Email;

namespace OpenPhotoAlbum.BusinessLogics
{
    public class RecoveringRequestManager
    {
        #region Singleton

        private static readonly RecoveringRequestManager _instance = new RecoveringRequestManager();

        private RecoveringRequestManager() { }

        public static RecoveringRequestManager Instance
        {
            get { return _instance; }
        }

        #endregion

        public bool AddNewRequest(User user)
        {
            RecoveringRequest request = new RecoveringRequest();
            request.RecoveringKey = Guid.NewGuid();
            request.RecoveringUserId = user.UserId;
			request.RecoveringRequestDate = DateTime.UtcNow;
            request.Used = false;

            DbLinqClassesDataContext context = new DbLinqClassesDataContext();
            context.RecoveringRequests.InsertOnSubmit(request);
            context.SubmitChanges();

            EmailPasswordRecoveryContentBuilders contentBuilder = new EmailPasswordRecoveryContentBuilders(request);
            EmailHtmlMessageBuilder messageBuilder = new EmailHtmlMessageBuilder(user.UserEmail);
            EmailDefaultSmtpClientBuilder clientBuilder = new EmailDefaultSmtpClientBuilder();

			try { EmailSender.Send(contentBuilder, messageBuilder, clientBuilder); }
			catch (Exception) { return false; }

            return true;
        }

        public RecoveringRequest GetRequest(Guid key)
        {
            return GetRequest(key, new DbLinqClassesDataContext());
        }

        public RecoveringRequest GetRequest(Guid key, DbLinqClassesDataContext context)
        {
            var results = from r in context.RecoveringRequests
                          where r.RecoveringKey.Equals(key)
                          select r;
            if (results == null || results.Count() == 0) { return null; }

            return results.First();
        }

        public void SetKeyUsed(DbLinqClassesDataContext context, Guid key)
        {
            RecoveringRequest request = GetRequest(key, context);
            if (request == null) { throw new InvalidKeyException(); }

            request.Used = true;
        }
    }
}
